package zyb.myproject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;

public class ClientOperateImpl implements ClientOperate {

	GoodsOperateImpl goi = new GoodsOperateImpl();

	// 用户登陆
	@Override
	public void login() throws Exception {

		System.out.println("********欢迎来到登陆界面********");
		Scanner sc = new Scanner(System.in);
		System.out.print("请输入账号：");
		String username = sc.next();
		System.out.print("请输入账号密码：");
		int password = sc.nextInt();

		// 进行用户名密码验证
		File file = new File(username);
		if (file.exists()) {
			FileInputStream fis = new FileInputStream(file);
			ObjectInputStream ois = new ObjectInputStream(fis);
			Client client = (Client) ois.readObject();
			if (client.getPassword() == password && username.equals(client.getUsername())) {
				System.out.println("恭喜您，登陆成功！");
				System.out.println("列出商品");
				goi.listGoods();// 显示商品
				ois.close();
			} else {
				System.out.println("用户密码错误,重新登陆！");
				login();
			}
		} else {
			System.out.println("该用户名不存在，自动跳到注册页面");
			regist();
		}

	}

	// 用户注册
	@Override
	public void regist() throws Exception {

		Scanner sc = new Scanner(System.in);
		System.out.print("请输入用户名：");
		String username = sc.next();
		System.out.print("请输入密码：");
		int password = sc.nextInt();
		System.out.print("请输入名字：");
		String name = sc.next();
		System.out.print("请输入年龄：");
		int age = sc.nextInt();
		Client newClient = new Client(username, password, name, age);
		System.out.println(newClient);
		File file = new File(newClient.getUsername());
		if (!file.exists()) {
			file.createNewFile();
			FileOutputStream fos = new FileOutputStream(file);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(new Client(username, password, name, age));
			oos.close();
			System.out.println("恭喜您注册成功！自动跳到登陆界面");
			login();
		} else {
			System.out.println("抱歉， 该用户名已经存在");
			regist();
		}

	}

}
